package org.praktika.api.service;

import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.praktika.api.dto.CityDto;
import org.praktika.api.entity.City;
import org.praktika.api.repository.CityRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class CityService {
    private final CityRepository cityRepository;
    private final ModelMapper modelMapper = new ModelMapper();

    @Transactional
    public CityDto saveCity  (CityDto cityDto){
        City city = modelMapper.map(cityDto, City.class);
        cityRepository.save(city);
        return modelMapper.map(city, CityDto.class);
    }

    public CityDto getCityDtoById(Long id){
        return modelMapper.map(getCityById(id), CityDto.class);
    }

    public City getCityById(Long id){
        Optional<City> city = cityRepository.findById(id);
        return city.orElseThrow(() -> new RuntimeException("No city found"));
    }

    @Transactional
    public CityDto updateCity(CityDto cityDto){
        City city = getCityById(cityDto.getId());
        city.setName(cityDto.getName());
        cityRepository.save(city);
        return modelMapper.map(city, CityDto.class);
    }

    @Transactional
    public void deleteCity(Long id){
        cityRepository.deleteById(id);
    }

    public List<CityDto> findAllCity(){
        List<City> cities = cityRepository.findAll();
        List<CityDto> cityDtos = new ArrayList<>();
        cities.forEach(city -> cityDtos.add(modelMapper.map(city, CityDto.class)));
        return cityDtos;
    }
}
